1. What is secure coding?
Answer: Secure coding is the practice of writing software that is resistant to vulnerabilities and cyber threats. It involves following security best practices to prevent attacks such as SQL injection, cross-site scripting (XSS), and buffer overflows.
2. Why is secure coding important?
Answer: Secure coding is essential to protect applications from security vulnerabilities, data breaches, and cyber-attacks. It ensures the confidentiality, integrity, and availability of software systems.
3. What are the top OWASP security risks?
Answer: The OWASP Top 10 is a list of the most critical web application security risks, including:
4. How can SQL injection be prevented?
Answer: SQL injection can be prevented using:
String query = "SELECT * FROM users WHERE username = ? AND password = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, username); stmt.setString(2, password); ResultSet rs = stmt.executeQuery();
5. How do you prevent cross-site scripting (XSS)?
Answer: XSS can be prevented by:
import org.owasp.encoder.Encode; String safeOutput = Encode.forHtml(userInput);
6. What is input validation, and why is it important?
Answer: Input validation ensures that user input meets predefined criteria before being processed. It helps prevent security issues such as SQL injection, XSS, and buffer overflows.
7. How do you securely store passwords in Java?
Answer: Passwords should be stored using strong hashing algorithms like BCrypt, PBKDF2, or Argon2. Example using BCrypt:
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String hashedPassword = encoder.encode("userPassword");
8. What is Cross-Site Request Forgery (CSRF), and how can it be prevented?
Answer: CSRF is an attack where unauthorized commands are transmitted from a user that the web application trusts. It can be prevented using:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().enable(); } }
9. How do you handle sensitive information in configuration files?
Answer: Sensitive information should never be stored in configuration files in plain text. Best practices include:
String dbPassword = System.getenv("DB_PASSWORD");
10. How do you securely handle exceptions in Java?
Answer: Secure exception handling includes:
try { int result = 10 / 0; } catch (Exception e) { logger.error("An error occurred: " + e.getMessage()); }
11. What is the principle of least privilege?
Answer: The principle of least privilege states that a user, process, or system component should only have the minimum privileges necessary to perform its function. This reduces the risk of unauthorized access and privilege escalation.
12. How do you prevent directory traversal attacks in Java?
Answer: Directory traversal attacks can be prevented by:
import java.io.File; import java.nio.file.Paths; public class SecureFileAccess { public static boolean isValidPath(String inputPath) { File file = new File(inputPath); String canonicalPath = file.getCanonicalPath(); return canonicalPath.startsWith("/secure/directory/"); } }
13. What are secure logging best practices?
Answer: Secure logging includes:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SecureLogger { private static final Logger logger = LoggerFactory.getLogger(SecureLogger.class); public static void logMessage(String message) { logger.info("User action logged: {}", message); } }
14. What is an insecure deserialization attack?
Answer: Insecure deserialization occurs when untrusted data is used to manipulate application logic or execute arbitrary code. It can be prevented by:
15. How do you securely deserialize objects in Java?
Answer: Use a safe approach like whitelisting allowed classes:
import java.io.*; public class SecureDeserialization { public static Object safeDeserialize(byte[] data) throws IOException, ClassNotFoundException { try (ByteArrayInputStream bis = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bis)) { Object obj = ois.readObject(); if (!(obj instanceof SafeClass)) { throw new SecurityException("Unauthorized deserialization attempt"); } return obj; } } }
16. What is a security token and how is it used?
Answer: A security token is a string used to authenticate and authorize users securely. Common types include JWT (JSON Web Token) and OAuth tokens.
17. How do you securely generate random numbers in Java?
Answer: Use `SecureRandom` instead of `java.util.Random` for cryptographic purposes.
import java.security.SecureRandom; public class SecureRandomExample { public static void main(String[] args) { SecureRandom secureRandom = new SecureRandom(); int randomInt = secureRandom.nextInt(100); System.out.println("Secure Random Number: " + randomInt); } }
18. What is Clickjacking, and how do you prevent it?
Answer: Clickjacking is an attack where a malicious website overlays an invisible iframe over a legitimate website to trick users into clicking on hidden elements. It can be prevented using:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.headers().frameOptions().deny(); } }
19. What are the best practices for API security?
Answer: Best practices include:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/secure/**").authenticated() .and() .oauth2Login(); } }
20. How do you prevent brute force attacks?
Answer: Brute force attacks can be mitigated using:
@Service public class LoginAttemptService { private final int MAX_ATTEMPTS = 5; private final Map attempts = new HashMap<>(); public void loginFailed(String username) { attempts.put(username, attempts.getOrDefault(username, 0) + 1); } public boolean isBlocked(String username) { return attempts.getOrDefault(username, 0) >= MAX_ATTEMPTS; } }
21. What is SQL Injection, and how do you prevent it?
Answer: SQL Injection is a vulnerability that allows attackers to execute arbitrary SQL commands. Prevention methods include:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class PreventSQLInjection { public static void main(String[] args) throws Exception { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/secure_db", "user", "password"); String query = "SELECT * FROM users WHERE username = ? AND password = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, "userInput"); stmt.setString(2, "passwordInput"); stmt.executeQuery(); } }
22. How do you protect sensitive data in Java applications?
Answer: Sensitive data can be protected by:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class SecureDataEncryption { public static void main(String[] args) throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey secretKey = keyGen.generateKey(); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedData = cipher.doFinal("SensitiveData".getBytes()); System.out.println(new String(encryptedData)); } }
23. What are the OWASP Top 10 vulnerabilities?
Answer: The OWASP Top 10 is a list of critical security risks for web applications:
24. What is Cross-Site Scripting (XSS) and how can it be mitigated?
Answer: XSS is a vulnerability that allows attackers to inject malicious scripts into web pages. Mitigation strategies include:
import org.apache.commons.text.StringEscapeUtils; public class PreventXSS { public static String sanitizeInput(String input) { return StringEscapeUtils.escapeHtml4(input); } }
25. What is a race condition, and how do you prevent it?
Answer: A race condition occurs when two threads access shared data and attempt to change it at the same time. Prevention methods include:
import java.util.concurrent.atomic.AtomicInteger; public class PreventRaceCondition { private AtomicInteger counter = new AtomicInteger(0); public void increment() { counter.incrementAndGet(); } }
26. What are the security best practices for file uploads?
Answer: Best practices include:
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class SecureFileUpload { public static void saveFile(byte[] fileData, String fileName) throws Exception { Path path = Paths.get("/uploads/" + fileName); Files.write(path, fileData); } }
27. What is the importance of secure password storage?
Answer: Secure password storage prevents attackers from easily accessing user credentials if the database is compromised. Use hashing algorithms like BCrypt, PBKDF2, or Argon2.
28. How do you handle exceptions securely in Java?
Answer: Secure exception handling practices include:
try { // Code } catch (Exception e) { logger.error("An error occurred: {}", e.getMessage()); }
29. How do you prevent open redirects in web applications?
Answer: Validate and whitelist redirect URLs before redirecting users.
30. What is CSRF, and how do you prevent it?
Answer: Cross-Site Request Forgery (CSRF) tricks a user into executing unwanted actions on a web application. Prevent it using:
31. What are some best practices for logging securely?
Answer: Best practices for secure logging include:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SecureLogging { private static final Logger logger = LoggerFactory.getLogger(SecureLogging.class); public static void main(String[] args) { logger.info("User login attempted"); } }
32. How do you validate user input in Java applications?
Answer: Use proper validation techniques:
import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; public class User { @NotNull private String name; @Email private String email; }
33. What is principle of least privilege in secure coding?
Answer: The principle of least privilege ensures that a user, process, or application is granted only the minimum access necessary to perform its tasks. This reduces the potential impact of security breaches.
34. How can you secure API keys in Java applications?
Answer: To secure API keys:
String apiKey = System.getenv("API_KEY");
35. What are some secure coding practices for dependency management?
Answer: Secure dependency management practices include:
36. How do you ensure secure configuration in Java applications?
Answer: Use secure configuration practices such as:
Properties config = new Properties(); config.load(new FileInputStream("secure-config.properties"));
37. What is the role of code reviews in secure coding?
Answer: Code reviews help identify security vulnerabilities early in the development process by:
38. How do you prevent Denial of Service (DoS) attacks in Java applications?
Answer: Prevent DoS attacks by:
import io.github.bucket4j.*; public class RateLimiterExample { private static final Bucket bucket = Bucket4j.builder().addLimit(Bandwidth.simple(10, Duration.ofMinutes(1))).build(); public static boolean allowRequest() { return bucket.tryConsume(1); } }
39. Why is parameterized SQL important for security?
Answer: Parameterized SQL helps prevent SQL injection by separating SQL logic from user input.
Example:PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE username = ?"); stmt.setString(1, userInput); ResultSet rs = stmt.executeQuery();
40. What is Cross-Site Request Forgery (CSRF), and how can you prevent it in Java applications?
Answer: CSRF is an attack where an unauthorized command is transmitted from a user that a web application trusts.
Prevention:
@Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); return http.build(); } }
41. What is the importance of secure session management?
Answer: Secure session management ensures that user sessions are protected against attacks such as session hijacking and fixation. Best practices include:
HttpSession session = request.getSession(); session.invalidate(); HttpSession newSession = request.getSession(true);
42. How can you secure REST APIs in Java?
Answer: Secure REST APIs by:
@RestController @RequestMapping("/api") public class SecureApiController { @GetMapping("/secure-data") @PreAuthorize("hasRole('ADMIN')") public String getSecureData() { return "Sensitive data"; } }
43. What is input sanitization, and why is it important?
Answer: Input sanitization removes malicious or unexpected data from user inputs to prevent attacks like XSS and SQL injection.
Example:import org.apache.commons.text.StringEscapeUtils; public class InputSanitizer { public static String sanitize(String input) { return StringEscapeUtils.escapeHtml4(input); } }
44. How do you enforce strong password policies in Java applications?
Answer: Enforce strong passwords by:
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordSecurity { public static void main(String[] args) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String hashedPassword = encoder.encode("SecurePass123!"); System.out.println("Hashed Password: " + hashedPassword); } }
45. How do you prevent XML External Entity (XXE) attacks in Java?
Answer: Disable external entity processing when parsing XML.
Example:DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
46. What are secure file upload best practices?
Answer: Secure file uploads by:
if (!file.getOriginalFilename().endsWith(".jpg") && !file.getOriginalFilename().endsWith(".png")) { throw new SecurityException("Invalid file type!"); }
47. How can you protect Java applications from deserialization attacks?
Answer: Prevent deserialization attacks by:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser")) { @Override protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!desc.getName().equals("com.example.SafeClass")) { throw new SecurityException("Unauthorized deserialization attempt"); } return super.resolveClass(desc); } };
48. Why is secure random number generation important?
Answer: Using secure random numbers prevents predictable values that attackers can exploit.
Example:import java.security.SecureRandom; SecureRandom secureRandom = new SecureRandom(); int randomInt = secureRandom.nextInt();
49. How do you securely store secrets in Java applications?
Answer: Store secrets securely by:
String dbPassword = System.getenv("DB_PASSWORD");
50. What is the importance of HTTP security headers?
Answer: HTTP security headers help mitigate attacks like XSS, clickjacking, and MIME sniffing.
Example:@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.headers() .contentSecurityPolicy("default-src 'self'") .and() .frameOptions().deny(); return http.build(); }
51. What is Cross-Origin Resource Sharing (CORS) and how do you secure it?
Answer: CORS is a security feature that controls how resources on a server can be requested from different domains. Secure it by restricting origins, methods, and headers.
Example:@Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("https://trusted.com") .allowedMethods("GET", "POST"); } }; } }
52. Why should you disable directory listing on a web server?
Answer: Directory listing exposes file structures, making it easier for attackers to find sensitive files.
Example (in Apache config):Options -Indexes
53. How can you prevent clickjacking in Java web applications?
Answer: Clickjacking can be prevented using the `X-Frame-Options` header.
Example:@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.headers().frameOptions().deny(); return http.build(); }
54. How do you securely log sensitive data?
Answer: Avoid logging sensitive information such as passwords, credit card numbers, and API keys.
Example:logger.info("User {} logged in", user.getUsername());
55. What is CSRF and how do you protect against it in Java?
Answer: Cross-Site Request Forgery (CSRF) tricks users into making unwanted actions. Protect against it using CSRF tokens.
Example:@Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); return http.build(); } }
56. Why should you validate all user inputs?
Answer: User input validation prevents security risks like SQL injection and XSS.
Example:@NotBlank @Size(max = 50) private String username;
57. How can you prevent IDOR (Insecure Direct Object References) vulnerabilities?
Answer: Implement proper authorization checks before granting access to resources.
Example:if (!currentUser.hasPermission(fileOwnerId)) { throw new SecurityException("Access denied"); }
58. What is the principle of least privilege in Java security?
Answer: The principle of least privilege means granting only the minimum necessary permissions to users and applications.
Example:DataSource ds = new BasicDataSource(); ds.setUser("readonly_user"); ds.setPassword("secure_password");
59. How do you securely store API keys in Java?
Answer: Store API keys in environment variables or secret management tools instead of hardcoding them.
Example:String apiKey = System.getenv("API_KEY");
60. What is an HTTP-only cookie and why is it important?
Answer: HTTP-only cookies prevent client-side JavaScript from accessing sensitive cookie data.
Example:Cookie cookie = new Cookie("sessionId", "secureValue"); cookie.setHttpOnly(true);
61. What is SQL Injection and how do you prevent it?
Answer: SQL Injection occurs when an attacker manipulates an SQL query via user input. Prevent it by using prepared statements.
Example:String sql = "SELECT * FROM users WHERE username = ?"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, username); ResultSet rs = stmt.executeQuery();
62. What are some secure password storage practices in Java?
Answer: Store passwords using strong hashing algorithms like BCrypt.
Example:String hashedPassword = new BCryptPasswordEncoder().encode(password);
63. How do you securely generate random tokens in Java?
Answer: Use `SecureRandom` instead of `Random` for cryptographic operations.
Example:SecureRandom secureRandom = new SecureRandom(); byte[] token = new byte[32]; secureRandom.nextBytes(token); String secureToken = Base64.getEncoder().encodeToString(token);
64. What is a security misconfiguration and how do you prevent it?
Answer: Security misconfigurations happen when default settings are not changed. Prevent it by disabling unused features and enforcing strong security settings.
Example:server.tomcat.accesslog.enabled=false server.servlet.session.cookie.secure=true
65. How do you implement rate limiting to prevent abuse?
Answer: Use a rate limiter like `Bucket4j` to restrict excessive requests.
Example:Bucket bucket = Bucket4j.builder() .addLimit(Bandwidth.classic(10, Refill.greedy(10, Duration.ofMinutes(1)))) .build();
66. How can you detect and prevent brute force attacks?
Answer: Implement account lockout after multiple failed login attempts.
Example:if (failedAttempts > 5) { lockAccount(user); }
67. What is HTTP Strict Transport Security (HSTS) and how do you implement it?
Answer: HSTS forces browsers to use HTTPS, preventing downgrade attacks.
Example:response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
68. How do you prevent XML External Entity (XXE) attacks in Java?
Answer: Disable external entity processing in XML parsers.
Example:SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
69. Why should you use Content Security Policy (CSP) headers?
Answer: CSP headers help mitigate Cross-Site Scripting (XSS) attacks by restricting allowed sources for scripts.
Example:response.setHeader("Content-Security-Policy", "default-src 'self'");
70. How can you secure REST APIs using API keys?
Answer: Validate API keys before processing requests.
Example:if (!isValidApiKey(request.getHeader("API-Key"))) { throw new SecurityException("Invalid API Key"); }
71. How can you prevent Cross-Site Request Forgery (CSRF) in Spring Boot?
Answer: Enable CSRF protection in Spring Security.
Example:@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().enable(); } }
72. How do you securely handle user authentication tokens?
Answer: Store tokens securely using HttpOnly cookies.
Example:Cookie cookie = new Cookie("authToken", token); cookie.setHttpOnly(true); response.addCookie(cookie);
73. What is Clickjacking and how do you prevent it?
Answer: Clickjacking tricks users into clicking elements they don’t intend to. Prevent it using X-Frame-Options.
Example:response.setHeader("X-Frame-Options", "DENY");
74. How do you validate user input to prevent injection attacks?
Answer: Use input validation techniques such as allowlists and regular expressions.
Example:if (!input.matches("^[a-zA-Z0-9_]+$")) { throw new IllegalArgumentException("Invalid input"); }
75. How do you encrypt sensitive data in Java?
Answer: Use AES encryption for secure data storage.
Example:Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encrypted = cipher.doFinal(data.getBytes());
76. How can you secure API endpoints from unauthorized access?
Answer: Use authentication and authorization mechanisms like JWT.
Example:@GetMapping("/secure-data") @PreAuthorize("hasRole('ADMIN')") public String getSecureData() { return "Secure Data"; }
77. What is a secure way to store API keys in Java applications?
Answer: Store API keys in environment variables or secure vaults.
Example:String apiKey = System.getenv("API_KEY");
78. How do you prevent sensitive data exposure in error messages?
Answer: Customize error handling to prevent stack traces from leaking information.
Example:@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred"); } }
79. Why should you use a security-focused logging framework?
Answer: Prevent logging sensitive information and use structured logging.
Example:logger.info("User {} logged in successfully", username);
80. How do you prevent Directory Traversal attacks?
Answer: Sanitize file paths and restrict file access.
Example:if (filePath.contains("..")) { throw new SecurityException("Invalid file path"); }